package com.dayu.finecomm.handler.cmd;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;

import java.net.InetSocketAddress;

import org.apache.commons.lang3.NotImplementedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.dayu.finecomm.protocol.SpecialCareChannelInboundAdapter;
import com.dayu.finecomm.protocol.pojo.TCommand;
import com.dayu.finecomm.protocol.pojo.TPacket;
import com.dayu.finecomm.protocol.pojo.TStation;
import com.dayu.finecomm.source.CollectSource;
import com.dayu.finecomm.utils.Helpers;

public class CMDSendHandler extends SpecialCareChannelInboundAdapter<TPacket> {

	static Logger LOGGER = LoggerFactory.getLogger(CMDSendHandler.class);

	CollectSource source;

	public CMDSendHandler(CollectSource source) {
		this.source = source;
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, TPacket packet)
			throws Exception {

		TStation station = source.collection().get(packet.id());

		if (station != null) {

			TCommand command = null;

			if ((command = station.historical.poll()) != null) {

				send(station.udp, station.address, ctx, command);
			}
		}

		ctx.fireChannelRead(packet);
	}

	public static void send(boolean udp, InetSocketAddress address,
			ChannelHandlerContext ctx, TCommand command) {

		if (command.command != null) {

			byte[] msg;

			LOGGER.info(String.format("Send command to %s: %s",
					command.station, JSON.toJSONString(command.command)));

			switch (command.format) {
			case 0:
				msg = command.command.getBytes();
				break;
			case 1:
				msg = Helpers.hexToBytes(command.command);
				break;
			default:
				throw new NotImplementedException("Unsupported format!");
			}

			if (udp) {
				ctx.writeAndFlush(new DatagramPacket(
						Unpooled.copiedBuffer(msg), address));
			} else {
				ctx.writeAndFlush(Unpooled.copiedBuffer(msg));
			}
		}

	}

}
